<template>
  <div class="mainBox" v-if="isAdd">
    <div class="contentBox">
      <el-form :model="detailModel" :rules="rules" ref="ruleFormRef">
        <el-form-item
          label="品牌"
          :label-width="formLabelWidth"
          prop="bizPlatform"
        >
          <el-checkbox-group v-model="detailModel.bizPlatform">
            <el-checkbox
              v-for="item in bizPlatformOptions"
              :key="item.value"
              :label="item.value"
              >{{ item.label }}</el-checkbox
            >
          </el-checkbox-group>
        </el-form-item>
        <el-form-item
          label="端口"
          :label-width="formLabelWidth"
          prop="appPlatform"
        >
          <el-checkbox-group v-model="detailModel.appPlatform">
            <el-checkbox
              v-for="item in appPlatformOptions"
              :key="item.value"
              :label="item.value"
              >{{ item.label }}</el-checkbox
            >
          </el-checkbox-group>
        </el-form-item>
        <el-form-item
          label="客群"
          :label-width="formLabelWidth"
          prop="userType"
        >
          <el-radio-group v-model="detailModel.userType">
            <el-radio :label="2">展业员</el-radio>
            <el-radio :label="1">车主</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label="用户"
          :label-width="formLabelWidth"
          prop="targetUid"
        >
          <el-radio-group v-model="detailModel.targetUid" @change="uidChange">
            <el-radio label="*">全部</el-radio>
            <el-radio label="1">指定群体</el-radio>
          </el-radio-group>
          <div class="txtBox">
            <el-input
              type="textarea"
              :autosize="{ minRows: 3, maxRows: 15 }"
              :formatter="(value) => value.replace(/[^\d|]/g, '')"
              v-model="targetUid"
              autocomplete="off"
              placeholder="用户ID，用多个'|'隔开"
              :disabled="isAllUid"
              style="width: 700px"
            />
            <el-upload
              :show-file-list="false"
              :auto-upload="false"
              accept=".txt"
              :on-change="openFile"
              :disabled="isAllUid"
            >
              <el-button link type="primary" size="small" :disabled="isAllUid"
                >上传</el-button
              >
            </el-upload>
          </div>
        </el-form-item>
        <el-form-item label="内容" :label-width="formLabelWidth" prop="content">
          <el-input
            v-model="detailModel.content"
            type="textarea"
            :autosize="{ minRows: 3, maxRows: 15 }"
            maxlength="50"
            placeholder="字数请控制在50汉字以内"
            style="width: 700px"
          />
        </el-form-item>
        <el-form-item
          label="生效时间"
          :label-width="formLabelWidth"
          prop="effectiveTime"
        >
          <el-date-picker
            v-model="detailModel.effectiveTime"
            type="datetime"
            placeholder="请选择生效时间"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item
          label="失效时间"
          :label-width="formLabelWidth"
          prop="expireTime"
        >
          <el-date-picker
            v-model="detailModel.expireTime"
            type="datetime"
            placeholder="请选择失效时间"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
      </el-form>
      <div class="subBtnBox">
        <el-button
          type="primary"
          color="#ea5b24"
          @click="formSubmit(ruleFormRef)"
          >保存</el-button
        >
        <el-button
          type="primary"
          color="#ea5b24"
          @click="emit('packConfigBack')"
          >返回</el-button
        >
      </div>
    </div>
  </div>
  <div class="mainBox" v-else>
    <div class="descriptionsBox">
      <el-descriptions :column="1" border>
        <el-descriptions-item
          label="品牌"
          label-align="right"
          label-class-name="labelCss"
        >
          {{ detailModel.bizPlatform }}
        </el-descriptions-item>
        <el-descriptions-item label="端口" label-align="right">
          {{ detailModel.appPlatform }}
        </el-descriptions-item>
        <el-descriptions-item label="客群" label-align="right">
          {{ detailModel.userType }}
        </el-descriptions-item>
        <el-descriptions-item label="用户" label-align="right">
          {{ detailModel.targetUid }}
          <div class="txtBox">
            {{ targetUid }}
          </div>
        </el-descriptions-item>
        <el-descriptions-item label="内容" label-align="right">
          {{ detailModel.content }}
        </el-descriptions-item>
        <el-descriptions-item label="生效时间" label-align="right">
          {{ detailModel.effectiveTime }}
        </el-descriptions-item>
        <el-descriptions-item label="失效时间" label-align="right">
          {{ detailModel.expireTime }}
        </el-descriptions-item>
      </el-descriptions>
      <div class="subBtnBox">
        <div v-if="marqueeState == 0" style="margin-right: 15px">
          <el-button
            type="primary"
            color="#ea5b24"
            @click="toExamine(1)"
            v-if="pinia.isShow[139]"
            >审核通过</el-button
          >
          <el-button
            type="primary"
            color="#ea5b24"
            @click="isShowDialogVisible = true"
            v-if="pinia.isShow[140]"
            >审核不通过</el-button
          >
        </div>
        <el-button
          type="primary"
          color="#ea5b24"
          @click="emit('packConfigBack')"
          >返回</el-button
        >

        <el-dialog
          v-model="isShowDialogVisible"
          title="跑马灯审核"
          center="true"
          modal="true"
          width="450px"
        >
          <el-form :model="toExamineModel">
            <el-form-item label="不通过原因">
              <el-input
                v-model="toExamineModel.checkNote"
                :autosize="{ minRows: 4 }"
                placeholder="请输入不通过原因."
                type="textarea"
                autocomplete="off"
              />
            </el-form-item>
          </el-form>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="isShowDialogVisible = false">取消</el-button>
              <el-button type="primary" color="#ea5b24" @click="toExamine(2)"
                >确定</el-button
              >
            </span>
          </template>
        </el-dialog>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from "vue";
import {
  findMarqueeInfoByIdApi,
  addMarqueeApi,
  checkMarqueeApi,
} from "../../../api/index";
import { ElMessage, FormInstance, FormRules } from "element-plus";
import { usePermissStore } from "../../../store/permiss";
const pinia = usePermissStore();

// 父级传递过来的参数
const props = defineProps({
  detaildData: Object,
});
//父级传递的方法
const emit = defineEmits(["packConfigBack"]);
const formLabelWidth = "200px";

//表单校验
const ruleFormRef = ref<FormInstance>();
const rules = reactive<FormRules>({
  bizPlatform: [{ required: true, message: "请选择品牌", trigger: "blur" }],
  appPlatform: [{ required: true, message: "请选择端口", trigger: "blur" }],
  userType: [{ required: true, message: "请选择客群", trigger: "blur" }],
  content: [{ required: true, message: "请输入内容", trigger: "blur" }],
  effectiveTime: [
    { required: true, message: "请选择生效时间", trigger: "blur" },
  ],
  expireTime: [{ required: true, message: "请选择失效时间", trigger: "blur" }],
});

// 判断是新增还是审核
let isAdd: any = ref(true);
let marqueeID = null;
// 跑马灯状态
let marqueeState: any = ref(null);

// 控制不通过原因输入框
let isShowDialogVisible = ref(false);

// 用户控制
let isAllUid = ref(true);
let targetUid = ref(null);

// 广告详情数据模型
let detailModel: any = reactive({
  bizPlatform: [],
  appPlatform: ["android", "ios"],
  userType: null,
  targetUid: "*",
  content: null,
  effectiveTime: null,
  expireTime: null,
});

// 审核参数模型
let toExamineModel: any = reactive({
  id: null,
  state: null,
  checkNote: null,
});

// 品牌枚举
const bizPlatformOptions: any = reactive([
  { value: "ybt", label: "壹佰通" },
  { value: "cxw", label: "车讯网" },
  { value: "wnsj", label: "华行通" },
  { value: "kyx", label: "阔悦行" },
]);

// 端口枚举
const appPlatformOptions: any = reactive([
  { value: "wx", label: "微信小程序" },
  { value: "alipay", label: "支付宝小程序" },
  { value: "android", label: "android客户端" },
  { value: "ios", label: "IOS客户端" },
]);

const uidChange = (val) => {
  switch (val) {
    case "*":
      isAllUid.value = true;
      targetUid.value = "";
      break;
    case "1":
      isAllUid.value = false;
      break;
  }
};

//上传txt文档
const openFile = (file) => {
  if (!file) {
    // 没有文件
    return false;
  } else if (!/\.(txt)$/.test(file.name.toLowerCase())) {
    // 格式根据自己需求定义
    ElMessage.error("上传格式不正确，请上传txt格式.");
    return false;
  }
  var reader = new FileReader();
  reader.onload = function () {
    if (reader.result) {
      //打印文件内容
      targetUid.value = reader.result;
    }
  };
  reader.readAsText(file.raw);
};

// 查询账单详情信息
const findNoticeInfo = (id) => {
  findMarqueeInfoByIdApi(id).then((res) => {
    if (res.data.code === 2000) {
      marqueeState.value = res.data.data.state;
      detailModel.appPlatform = res.data.data.appPlatform.replaceAll("|", ",");
      detailModel.bizPlatform = res.data.data.bizPlatform.replaceAll("|", ",");
      if (res.data.data.userType == 1) {
        detailModel.userType = "车主";
      } else {
        detailModel.userType = "代理员";
      }
      if (res.data.data.targetUid == "*") {
        detailModel.targetUid = "全部用户";
      } else {
        detailModel.targetUid = "指定群体";
        targetUid.value = res.data.data.targetUid;
      }
      detailModel.content = res.data.data.content;
      detailModel.effectiveTime = res.data.data.effectiveTime;
      detailModel.expireTime = res.data.data.expireTime;
    } else {
      ElMessage.error("查询失败");
    }
  });
};

// 添加提交
const formSubmit = (formEl) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      if (detailModel.targetUid != "*") {
        if (targetUid.value) {
          detailModel.targetUid = targetUid.value;
        } else {
          ElMessage.warning("请输入用户ID.");
          return;
        }
      }
      if (detailModel.bizPlatform) {
        detailModel.bizPlatform = detailModel.bizPlatform.join("|");
      }
      if (detailModel.bizPlatform) {
        detailModel.appPlatform = detailModel.appPlatform.join("|");
      }
      addMarqueeApi(detailModel).then((res) => {
        if (res.data.code === 2000) {
          ElMessage({
            message: "添加成功.",
            type: "success",
          });
          marqueeID = res.data.data;
          findNoticeInfo(marqueeID);
          isAdd.value = false;
        } else {
          detailModel.bizPlatform = detailModel.bizPlatform.split("|");
          detailModel.appPlatform = detailModel.appPlatform.split("|");
          switch (res.data.code) {
            case 4001:
              ElMessage.error("指定用户文本格式不合法.");
              break;
            case 4002:
              ElMessage.error("生效时间必须在失效时间之前.");
              break;
            case 4003:
              ElMessage.error("生效时间段有重叠，添加失败.");
              break;
            default:
              ElMessage.error("添加失败.");
              break;
          }
        }
      });
    } else {
      return false;
    }
  });
};

// 审核
const toExamine = (state) => {
  if (
    state == 2 &&
    (toExamineModel.checkNote == "" || toExamineModel.checkNote == null)
  ) {
    ElMessage.error("请输入不通过原因.");
    return;
  }
  toExamineModel.state = state;
  toExamineModel.id = marqueeID;
  checkMarqueeApi(toExamineModel).then((res) => {
    if (res.data.code === 2000) {
      ElMessage({
        message: "审核成功.",
        type: "success",
      });
      isShowDialogVisible.value = false;
      emit("packConfigBack");
    } else {
      ElMessage.error("审核失败.");
    }
  });
};

onMounted(() => {
  if (props.detaildData.id) {
    marqueeID = props.detaildData.id;
    isAdd.value = false;
    findNoticeInfo(marqueeID);
  } else {
    isAdd.value = true;
    // 获取当前时间
    let nowTime = new Date().getTime();
    detailModel.effectiveTime = pinia.timeConversion(nowTime);
  }
});
</script>

<style scoped>
.mainBox {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding-bottom: 40px;
  /* border: 1px solid red; */
  width: 100%;
}
.contentBox {
  background-color: #ffffff;
  border-radius: 32px;
  box-shadow: 0px 4px 4px 0px rgba(0, 0, 0, 0.1);
  padding: 40px;
  width: 900px;
  display: flex;
  flex-direction: column;
}

.descriptionsBox {
  /* border: 1px solid red; */
  width: 700px;
  padding-bottom: 40px;
  display: flex;
  flex-direction: column;
}

.txtBox {
  display: flex;
  word-break: break-all;
  width: 100%;
}

.previewImgBox {
  border: 1px solid #c0c4cc;
  max-width: 100px;
}

.previewImg {
  width: 100%;
  height: 100%;
}

.subBtnBox {
  width: 100%;
  margin-top: 40px;
  display: flex;
  justify-content: center;
}

:deep(.labelCss) {
  width: 100px;
}
</style>
